from django.shortcuts import render

from rest_framework.generics import GenericAPIView, CreateAPIView
from rest_framework.response import Response

from . import serializers
from . import models


# Create your views here.

class HeadlineTextView(GenericAPIView):
    serializer_class = serializers.HeadlineTextSerializer

    # queryset = models.HeadlineText.objects().get().all()
    def get(self, request):
        hlt = models.HeadlineText.objects.order_by("-c_time").all()
        s_o = serializers.HeadlineTextSerializer(hlt, many=True)
        hltl = []
        for i in s_o.data:
            data = {
                "id": i["id"],
                "title": i["title"],
                "c_time": i["c_time"],
                "img": i["img"],
                "intro": i["intro"],
            }
            # if i["id"] == 1:
            hltl.append(data)
        return Response(hltl)


class HeadlineDetailView(GenericAPIView):
    serializer_class = serializers.HeadlineDetailSerializer

    def get(self, request):
        new_id = int(request.query_params["new_id"])
        htd = models.HeadlineText.objects.get(id=new_id)
        s_o = serializers.HeadlineDetailSerializer(htd)
        return Response(s_o.data)


class HeadlineDetaiCommentlView(GenericAPIView):
    serializer_class = serializers.HeadlineDetaiCommentlSerializer

    def get(self, request):
        new_id = request.query_params["new_id"]
        hlc = models.HeadlineComment.objects.filter(hl_id=new_id)
        hlc_list = []
        for i in hlc:
            i = i.__dict__
            s_o = serializers.HeadlineDetaiCommentlSerializer(data=i)
            if not s_o.is_valid():
                return Response({"message": s_o.errors})
            hlc_list.append(s_o.data)
        s_o = serializers.HeadlineDetaiCommentlSerializer(data=hlc_list, many=True)
        if not s_o.is_valid():
            return Response({"message": s_o.errors})
        return Response(s_o.data)

    def post(self, request):
        data = request.data
        s_o = serializers.HeadlineDetaiCommentlSerializer(data=data)
        if not s_o.is_valid():
            return Response({"message": s_o.errors})
        try:
            s_o.save()
        except Exception as e:
            print(e)
        return Response({"message": "ok"})


class AddHeadline(CreateAPIView):
    serializer_class = serializers.HeadlineTextSerializer
